package com.zhao.fishingguideserver.service.impl;

import com.zhao.fishingguideserver.service.FileUploadService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传服务实现类
 */
@Service
public class FileUploadServiceImpl implements FileUploadService {
    
    // 文件存储路径
    private static final String UPLOAD_PATH = "uploads/images/";
    
    // 允许的图片类型
    private static final String[] ALLOWED_IMAGE_TYPES = {
        "image/jpeg", "image/jpg", "image/png", "image/gif", "image/webp"
    };
    
    @Override
    public String uploadImage(MultipartFile file) throws IOException {
        // 验证文件
        validateFile(file);
        
        // 生成唯一文件名
        String fileName = generateFileName(file.getOriginalFilename());
        
        // 创建目录
        File uploadDir = new File(UPLOAD_PATH);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        
        // 保存文件
        File targetFile = new File(uploadDir, fileName);
        file.transferTo(targetFile);
        
        // 返回访问URL
        return "/uploads/images/" + fileName;
    }
    
    @Override
    public boolean deleteImage(String imageUrl) {
        try {
            if (imageUrl == null || !imageUrl.startsWith("/uploads/images/")) {
                return false;
            }
            
            String fileName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
            File file = new File(UPLOAD_PATH + fileName);
            
            if (file.exists()) {
                return file.delete();
            }
            return true; // 文件不存在也算删除成功
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    /**
     * 验证文件
     */
    private void validateFile(MultipartFile file) {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }
        
        // 验证文件类型
        String contentType = file.getContentType();
        if (contentType == null) {
            throw new IllegalArgumentException("无法识别文件类型");
        }
        
        boolean isAllowedType = false;
        for (String allowedType : ALLOWED_IMAGE_TYPES) {
            if (contentType.equalsIgnoreCase(allowedType)) {
                isAllowedType = true;
                break;
            }
        }
        
        if (!isAllowedType) {
            throw new IllegalArgumentException("只支持 jpg、png、gif、webp 格式的图片");
        }
        
        // 验证文件大小 (2MB)
        if (file.getSize() > 2 * 1024 * 1024) {
            throw new IllegalArgumentException("文件大小不能超过2MB");
        }
    }
    
    /**
     * 生成唯一文件名
     */
    private String generateFileName(String originalFilename) {
        String extension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        return UUID.randomUUID().toString() + extension;
    }
}
